package cn.linkai.star.graph.core.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.linkai.star.graph.core.dto.common.Result;
import cn.linkai.star.graph.core.dto.common.ResultCode;
import cn.linkai.star.graph.core.pojo.User;
import cn.linkai.star.graph.core.utils.JWTUtils;
import cn.linkai.star.graph.core.utils.UserUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String header = request.getHeader (HttpHeaders.AUTHORIZATION);
        if(StrUtil.isEmpty (header)){
            writeErrMsg(response);
            return false;
        }

        //校验 token
        if(!JWTUtils.verify(header)){
            writeErrMsg(response);
            return false;
        }

        //将用户存入ThreadLocal中
        User user = JWTUtils.getUser (header);
        UserUtils.setUser (user);
        return true;
    }

    private void writeErrMsg(HttpServletResponse response) {
        //设置状态码以及响应头
        response.setStatus (HttpStatus.UNAUTHORIZED.value ());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding (StandardCharsets.UTF_8.name ());
        //设置响应体内容
        try (PrintWriter writer = response.getWriter()){
            Result<Object> result = Result.failed (ResultCode.ACCESS_UNAUTHORIZED);
            writer.write (JSONUtil.toJsonStr (result));
            writer.flush ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion (request, response, handler, ex);
    }
}
